/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package coursesmaritimes.obtention.client;

import java.io.StringReader;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

/**
 * @author csuma
 */
public class ParserXml {

    static Document doc = null;
    static DocumentBuilder builder = null;

    /**
     * Exploite le XML
     */
    public ParserXml()  {
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            System.out.println(ex.getMessage());
        }
    }

    /**
     * Charger les données XML dans un object GPX
     * @param strXml : la chaine XML
     * @return l'objet GXP construit
     */
    public  GPX getFromXml(String strXml) {
        StringReader reader = new StringReader(strXml);
        InputSource inputSource = new InputSource(reader);

        GPX gpx = new GPX();

        try {
            doc = builder.parse(inputSource);

            NodeList participantList = doc.getElementsByTagName("participant");

            for (int i = 0; i < participantList.getLength(); i++) {
                Element participantElement = (Element) participantList.item(i);
                gpx.participant = participantElement.getAttribute("id");
                NodeList trkptListt = participantElement.getElementsByTagName("trkpt");
                Element trkptElement = (Element) trkptListt.item(0);
                gpx.lat = trkptElement.getAttribute("lat");
                gpx.lon = trkptElement.getAttribute("lon");
                // Et la date aussi ( à vérifier )
                NodeList timeList = participantElement.getElementsByTagName("time");
                Element timeElement = (Element)timeList.item(0);
                gpx.date = timeElement.getTextContent();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return gpx;
    }
}